<template>
  <div class="exam-detail" v-loading="loading">
    <div class="exam-header">
      <div class="exam-info">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/exams' }">考试中心</el-breadcrumb-item>
          <el-breadcrumb-item>{{ exam.title }}</el-breadcrumb-item>
        </el-breadcrumb>
        
        <h1>{{ exam.title }}</h1>
        <div class="exam-meta">
          <span><el-icon><Document /></el-icon> 题目数量: {{ exam.questionCount }}</span>
          <span><el-icon><Clock /></el-icon> 考试时长: {{ exam.duration }} 分钟</span>
          <span><el-icon><Star /></el-icon> 总分: {{ exam.totalScore }} 分</span>
        </div>
      </div>
      
      <div class="exam-timer">
        <div class="timer-display">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(remainingTime) }}</span>
        </div>
        <div class="timer-actions">
          <el-button type="primary" @click="submitExam">提交试卷</el-button>
        </div>
      </div>
    </div>

    <div class="exam-content">
      <div class="question-list">
        <div class="question-nav">
          <div 
            v-for="(question, index) in questions" 
            :key="question.id"
            class="question-number"
            :class="{ 
              active: currentQuestionIndex === index,
              answered: answers[question.id] !== undefined,
              marked: markedQuestions.includes(question.id)
            }"
            @click="goToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
        
        <div class="question-actions">
          <el-button @click="markQuestion" :type="isMarked ? 'warning' : 'default'">
            {{ isMarked ? '取消标记' : '标记题目' }}
          </el-button>
          <el-button @click="goToNextUnanswered">下一未答</el-button>
        </div>
      </div>

      <div class="question-content">
        <div v-if="currentQuestion" class="question-card">
          <div class="question-header">
            <h3>第 {{ currentQuestionIndex + 1 }} 题 ({{ getQuestionTypeText(currentQuestion.type) }})</h3>
            <span class="question-score">{{ currentQuestion.score }} 分</span>
          </div>
          
          <div class="question-body">
            <p class="question-title">{{ currentQuestion.title }}</p>
            
            <div v-if="currentQuestion.type === 'single'" class="options">
              <el-radio-group v-model="answers[currentQuestion.id]" @change="onAnswerChange">
                <el-radio 
                  v-for="option in currentQuestion.options" 
                  :key="option.id"
                  :label="option.id"
                >
                  {{ option.label }}. {{ option.content }}
                </el-radio>
              </el-radio-group>
            </div>
            
            <div v-else-if="currentQuestion.type === 'multiple'" class="options">
              <el-checkbox-group v-model="answers[currentQuestion.id]" @change="onAnswerChange">
                <el-checkbox 
                  v-for="option in currentQuestion.options" 
                  :key="option.id"
                  :label="option.id"
                >
                  {{ option.label }}. {{ option.content }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            
            <div v-else-if="currentQuestion.type === 'text'" class="text-answer">
              <el-input
                v-model="answers[currentQuestion.id]"
                type="textarea"
                :rows="4"
                placeholder="请输入您的答案"
                @input="onAnswerChange"
              />
            </div>
          </div>

          <div class="question-navigation">
            <el-button 
              :disabled="currentQuestionIndex === 0"
              @click="previousQuestion"
            >
              上一题
            </el-button>
            <el-button 
              :disabled="currentQuestionIndex === questions.length - 1"
              @click="nextQuestion"
            >
              下一题
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="exam-footer">
      <div class="progress-info">
        <span>已答 {{ answeredCount }} / {{ questions.length }} 题</span>
        <span>标记 {{ markedQuestions.length }} 题</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { examApi } from '@/api/exam'
import { Document, Clock, Star } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const exam = ref({
  id: '',
  title: '',
  questionCount: 0,
  duration: 0,
  totalScore: 0
})

const questions = ref([])
const currentQuestionIndex = ref(0)
const answers = ref({})
const markedQuestions = ref([])
const remainingTime = ref(0)
const timer = ref(null)
const loading = ref(false)

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

const answeredCount = computed(() => {
  return Object.keys(answers.value).filter(key => answers.value[key] !== undefined && answers.value[key] !== '').length
})

const isMarked = computed(() => {
  return currentQuestion.value && markedQuestions.value.includes(currentQuestion.value.id)
})

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'single': '单选题',
    'multiple': '多选题',
    'text': '简答题'
  }
  return typeMap[type] || '未知题型'
}

// 启动计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      submitExam()
    }
  }, 1000)
}

// 停止计时器
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

// 跳转到指定题目
const goToQuestion = (index) => {
  currentQuestionIndex.value = index
}

// 标记/取消标记题目
const markQuestion = () => {
  if (!currentQuestion.value) return
  
  const questionId = currentQuestion.value.id
  const index = markedQuestions.value.indexOf(questionId)
  
  if (index > -1) {
    // 取消标记
    markedQuestions.value.splice(index, 1)
  } else {
    // 标记题目
    markedQuestions.value.push(questionId)
  }
}

// 跳转到下一未答题
const goToNextUnanswered = () => {
  for (let i = currentQuestionIndex.value + 1; i < questions.value.length; i++) {
    const question = questions.value[i]
    if (!answers.value[question.id]) {
      currentQuestionIndex.value = i
      return
    }
  }
  
  // 如果后面没有未答题，查找前面的
  for (let i = 0; i < currentQuestionIndex.value; i++) {
    const question = questions.value[i]
    if (!answers.value[question.id]) {
      currentQuestionIndex.value = i
      return
    }
  }
  
  ElMessage.info('所有题目都已作答')
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

// 答案变化处理
const onAnswerChange = () => {
  // 答案变化时可以做一些处理
}

// 提交考试
const submitExam = async () => {
  try {
    await ElMessageBox.confirm(
      `您已回答 ${answeredCount.value} 道题，还有 ${questions.value.length - answeredCount.value} 道题未答。确定要提交试卷吗？`,
      '提示',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '继续答题',
        type: 'warning'
      }
    )
    
    stopTimer()
    
    const submitData = {
      examId: exam.value.id,
      answers: answers.value
    }
    
    await examApi.submitAnswer(submitData)
    ElMessage.success('试卷提交成功')
    
    // 跳转到考试结果页面
    router.push(`/exams/${exam.value.id}/result`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交试卷失败:', error)
      ElMessage.error('提交试卷失败')
    }
  }
}

// 开始考试
const startExam = async (examId) => {
  loading.value = true
  try {
    // 获取考试详情
    const examData = await examApi.getExamDetail(examId)
    exam.value = examData
    
    // 获取考试题目
    const questionsData = await examApi.getExamQuestions(examId)
    questions.value = questionsData || []
    
    // 设置考试时间（秒）
    remainingTime.value = exam.value.duration * 60
    
    // 启动计时器
    startTimer()
  } catch (error) {
    console.error('加载考试失败:', error)
    ElMessage.error('加载考试失败')
  } finally {
    loading.value = false
  }
}

// 组件卸载时清理
onUnmounted(() => {
  stopTimer()
})

// 监听路由变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      startExam(newId)
    }
  },
  { immediate: true }
)

onMounted(() => {
  // 页面加载时启动考试
})
</script>

<style scoped>
.exam-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.exam-header h1 {
  margin: 10px 0;
  color: #333;
}

.exam-meta {
  display: flex;
  gap: 20px;
  color: #666;
}

.exam-meta span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.exam-timer {
  text-align: right;
}

.timer-display {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 15px;
}

.exam-content {
  display: flex;
  flex: 1;
  gap: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow: hidden;
}

.question-list {
  width: 250px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e1e1e1;
  padding-right: 20px;
}

.question-nav {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.question-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: bold;
}

.question-number:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.question-number.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.question-number.answered {
  background: #67c23a;
  color: white;
  border-color: #67c23a;
}

.question-number.marked {
  background: #e6a23c;
  color: white;
  border-color: #e6a23c;
}

.question-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.question-content {
  flex: 1;
  overflow-y: auto;
}

.question-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1e1e1;
  margin-bottom: 20px;
}

.question-header h3 {
  margin: 0;
  color: #333;
}

.question-score {
  color: #f56c6c;
  font-weight: bold;
}

.question-title {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
  color: #333;
}

.options {
  margin-bottom: 30px;
}

.options .el-radio,
.options .el-checkbox {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  transition: background 0.3s;
}

.options .el-radio:hover,
.options .el-checkbox:hover {
  background: #f5f7fa;
}

.text-answer {
  margin-bottom: 30px;
}

.question-navigation {
  display: flex;
  justify-content: space-between;
  padding-top: 20px;
  border-top: 1px solid #e1e1e1;
}

.exam-footer {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.progress-info {
  display: flex;
  gap: 20px;
  color: #666;
}

@media (max-width: 768px) {
  .exam-content {
    flex-direction: column;
  }
  
  .question-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e1e1e1;
    padding-right: 0;
    padding-bottom: 20px;
  }
  
  .question-nav {
    grid-template-columns: repeat(10, 1fr);
  }
  
  .exam-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .exam-timer {
    text-align: left;
  }
}
</style>